package cn.wgx.module.ent.service;

import cn.wgx.common.base.IBaseService;
import cn.wgx.common.entity.ent.Enterprise;
import cn.wgx.module.ent.mapper.EnterpriseMapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EntDeptService extends IBaseService<EnterpriseMapper, Enterprise> {

    //新增部门包含多个步骤
    public boolean save(Enterprise enterprise) {
        //1.注册企业、部门
        if (enterprise.getPid() != 0) {//创建部门
            Integer top_pid = baseMapper.selectById(enterprise.getPid()).getTop_pid();
            if (top_pid != 0) {//多级
                enterprise.setTop_pid(top_pid);//注册企业时，自动填写top_pid
            } else {//二级
                enterprise.setTop_pid(enterprise.getPid());
            }
        }
        boolean b = super.save(enterprise);
        if (b) {
            //初始化部门的entcode
            iniEntCode(enterprise);
        }

        return b;
    }

    //设置entCode, E父ID + E自己ID + E
    private boolean iniEntCode(Enterprise enterprise) {
        if (enterprise.getEnt_id() == null || enterprise.getEnt_id().equals(0)) {
            return false;
        }
        //初始化entcode
        String pcode = "E";
        if (0 != enterprise.getPid()) {//子集
            Enterprise enterprise1 = getById(enterprise.getPid());
            if (enterprise1 != null) {
                pcode = enterprise1.getEntCode();
            }
        }
        enterprise.setEntCode(pcode + enterprise.getEnt_id() + "E");
        Enterprise enterprise1 = new Enterprise();
        enterprise1.setEnt_id(enterprise.getEnt_id());
        enterprise1.setEntCode(enterprise.getEntCode());
        enterprise1.setCode(enterprise.getCode());
        baseMapper.updateById(enterprise1);
        return true;
    }

    //根据entCode查找
    public Enterprise getOneByCode(String entCode) {
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper();
        queryWrapper.like("entCode", entCode);
        List<Enterprise> enterprises = list(queryWrapper);
        if (!enterprises.isEmpty()) {
            return enterprises.get(0);
        }
        return null;
    }

    //根据entCode查找
    public List<Enterprise> getListByEntCode(String entCode) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("entCode", entCode);
        List<Enterprise> enterprises = list(queryWrapper);
        if (!enterprises.isEmpty()) {
            return enterprises;
        }
        return null;
    }

    //根据entCode删除部门
    public boolean del(String entCode) {
        List<Enterprise> listByEntCode = getListByEntCode(entCode);
        for (Enterprise enterprise : listByEntCode) {
            return super.removeById(enterprise.getEnt_id());
        }
        return false;
    }

}
